<template>
  <el-popover :visible="routerParams.isAdd == 0" placement="top" :width="120">
    <p>还未添加好友 是否添加?</p>
    <div style="text-align: center; margin: 0">
      <el-button size="small" type="primary" @click="add">添加</el-button>
    </div>
    <template #reference>
      <div class="title1">
        {{ routerParams.name }}
      </div>
    </template>
  </el-popover>


  <div class="container">
    <div class="content">
      <div class="item item-center"><span>昨天 12:35</span></div>
      <div class="item item-center"><span>你已添加了凡繁烦，现在可以开始聊天了。</span></div>
    </div>
    <div class="input-area">
      <el-icon :size="20" @click="toPhone"><VideoCamera /></el-icon>
      <textarea name="text" id="textarea" v-model="value" @keyup.enter.native="sendMessage"></textarea>
      <div class="button-area">
        <button id="send-btn" @click="sendMessage">发 送</button>
      </div>
    </div>
  </div>

  <el-dialog v-model="addFriendShow" title="添加好友" style="width:500px;">
    <el-form>
      <el-form-item label="添加到的分组" label-width="140px">
        <el-select v-model="friend.friendGroupId" placeholder="分组" @click="get">
          <el-option v-for="item in group" :key="item.friendGroupId" :label="item.name" :value="item.friendGroupId" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="quitFriend">退出</el-button>
        <el-button type="primary" @click="addFriend1">
          添加
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {onMounted, reactive, Ref, ref, watchEffect} from "vue";
import {useRouter} from "vue-router";
import {userInfo} from "../../utils/constant";
import {MessageDto, send, MessageType, callbacks, webSocket, webSocketLink} from "../../utils/webSocket";
import {getChatList, setRead} from "../../service/ChatApi";
import {error, success} from "../../utils/messageUtil";
import {getUserAccount} from "../../service/AccountApi";
import {addFriend, addFriendId, getFriendGroup} from "../../service/TieApi";
import emitter from "../../utils/eventbus";

const router = useRouter();

const routerParams:Ref<any> = ref({})

const group:Ref<any[]> = ref([])

const toPhone = ()=>{
  emitter.emit("phone",{
    sendUserSocketDto: {
      userId: userInfo().id,
      name: userInfo().name
    },
    acceptUserSocketDto: {
      userId: (routerParams.value as any).sessionId,
      name: (routerParams.value as any).name
    },
    message: '',
    type: MessageType.TOPHONE,
    sessionType: (routerParams.value as any).sessionType
  })
}

const add = () => {
  addFriendShow.value = true;
  friend.userId = (routerParams.value as any).sessionId;
}

const quitFriend = ()=>{
  addFriendShow.value = false
  friend.userId = '';
  friend.friendGroupId = '';
}

const addFriend1 = ()=>{
  addFriendId(friend).then(d=>{
    if(d.data.code==200){
      success("添加请求发送成功")
      addFriendShow.value = false;
      friend.userId = '';
      friend.friendGroupId = '';
    }else{
      error(d.data.message)
    }
  }).catch(()=>{
    error("网络异常")
  })
}

const get = ()=>{
  getFriendGroup().then(d=>{
    if(d.data.code==200){
      group.value = d.data.date
    }else{
      error(d.data.message)
    }
  }).catch(()=>{
    error("网络异常")
  })
}

const addFriendShow = ref(false)
const friend = reactive(  {
  userId:'',
  friendGroupId:''
})

//加载聊天数据
const LoadChatList = () => {
  getChatList({
    acceptId: (routerParams.value as any).sessionId,
    sessionType: (routerParams.value as any).sessionType
  }).then(d => {
    if (d.data.code != 200) {
      error(d.data.message);
      return
    }
    const list: [] = d.data.date;
    list.forEach(item => {
      //如果是群聊信息
      if((routerParams.value as any).sessionType == 'GROUP'){
        if ((item as any).send.sessionId === userInfo().id) {
          createRight((item as any).send.avatar, (item as any).message)
        }else{
          createLeft((item as any).send.avatar, (item as any).message)
        }
      }
      if((routerParams.value as any).sessionType == 'ALONG'){
        if ((item as any).accept.sessionId === userInfo().id) {
          createLeft((item as any).send.avatar, (item as any).message)
        }
        if ((item as any).send.sessionId === userInfo().id) {
          createRight((item as any).send.avatar, (item as any).message)
        }
      }
    })

    //滚动条置底
    let height = (document.querySelector('.content') as any).scrollHeight;
    (document.querySelector(".content") as any).scrollTop = height;
  })
}

//清除聊天数据
const clearChatList = () => {
  let e = document.querySelector('.content');
  let child = e?.lastElementChild;
  while (child) {
    e?.removeChild(child);
    child = e?.lastElementChild;
  }
}

// 监听路由参数变化
watchEffect(() => {
  if(router.currentRoute.value.name == 'chat') {
    (routerParams as any).value = router.currentRoute.value.query;

    callbacks.getMessage = (messageDto: MessageDto) => {

      //必须是在当前的页面才进行处理
      if(router.currentRoute.value.name === 'chat') {
        accept(messageDto);
      }

    }

    clearChatList();

    LoadChatList();
  }
})

const value = ref("");

const createLeft = (avatar: string, message: string) => {
  let item = document.createElement('div');
  item.className = 'item item-left';
  item.innerHTML = `
                    <div class="avatar" @click="ki">
                        <img src="${import.meta.env.VITE_APP_BASE_API + "/common/file/loadFileId?fileId=" + avatar}" />
                    </div>
                    <div class="bubble bubble-left">
                        ${message}
                    </div>
                    `;
  (document.querySelector('.content') as any).appendChild(item);
}

const createRight = (avatar: string, message: string) => {
  let item = document.createElement('div');
  item.className = 'item item-right';
  item.innerHTML = `<div class="bubble bubble-right">
                        ${message}
                    </div>
                    <div class="avatar">
                        <img src="${import.meta.env.VITE_APP_BASE_API + "/common/file/loadFileId?fileId=" + avatar}" />
                    </div>`;
  (document.querySelector('.content') as any).appendChild(item);
}

const accept = (messageDto: MessageDto) => {

  //接受关于自己会话的消息
  if(messageDto.sessionType == 'ALONG'){
    if((routerParams.value as any).sessionId == messageDto.sendUserSocketDto.userId) {
      createLeft((routerParams.value as any).avatar, messageDto.message);
    }
  }

  //群消息
  if(messageDto.sessionType == 'GROUP'){
    if((routerParams.value as any).sessionId == messageDto.acceptUserSocketDto.userId){
      getUserAccount({
        userId: messageDto.sendUserSocketDto.userId
      }).then(d=>{
        if(d.data.code == 200){
          createLeft(d.data.date.avatar, messageDto.message);
        }else{
          error(d.data.message);
        }
      }).catch(()=>{
        error("网络错误")
      })
    }
  }

  //滚动条置底
  let height = (document.querySelector('.content') as any).scrollHeight;
  (document.querySelector(".content") as any).scrollTop = height;
}

const sendMessage = () => {

  createRight(userInfo().avatar, value.value);

  //滚动条置底
  let height = (document.querySelector('.content') as any).scrollHeight;
  (document.querySelector(".content") as any).scrollTop = height;

  let messageDte: MessageDto = {
    sendUserSocketDto: {
      userId: userInfo().id,
      name: userInfo().name
    },
    acceptUserSocketDto: {
      userId: (routerParams.value as any).sessionId,
      name: (routerParams.value as any).name
    },
    message: value.value,
    type: MessageType.TEXT,
    sessionType: (routerParams.value as any).sessionType
  }
  send(messageDte);

  value.value=''
}

</script>

<style>
.title1 {
  width: 100%;
  height: 40px;
  text-align: center;
  background-color: rgb(26, 255, 0);
  font-size: 24px;
}

.container {
  height: calc(100vh - 180px);
  width: 100%;
  border-radius: 4px;
  border: 0.5px solid #e0e0e0;
  background-color: #f5f5f5;
  display: flex;
  flex-flow: column;
  overflow: hidden;

  margin:0px;
  background-size:cover;
  background-attachment:fixed;
}

.content {
  width: calc(100% - 40px);
  padding: 20px;
  overflow-y: scroll;
  flex: 1;
}

.content:hover::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1);
}

.bubble {
  max-width: 400px;
  padding: 10px;
  border-radius: 5px;
  position: relative;
  color: #000;
  word-wrap: break-word;
  word-break: normal;
}

.item-left .bubble {
  margin-left: 15px;
  background-color: #fff;
}

.item-left .bubble:before {
  content: "";
  position: absolute;
  width: 0;
  height: 0;
  border-left: 10px solid transparent;
  border-top: 10px solid transparent;
  border-right: 10px solid #fff;
  border-bottom: 10px solid transparent;
  left: -20px;
}

.item-right .bubble {
  margin-right: 15px;
  background-color: #9eea6a;
}

.item-right .bubble:before {
  content: "";
  position: absolute;
  width: 0;
  height: 0;
  border-left: 10px solid #9eea6a;
  border-top: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 10px solid transparent;
  right: -20px;
}

.item {
  margin-top: 15px;
  display: flex;
  width: 100%;
}

.item.item-right {
  justify-content: flex-end;
}

.item.item-center {
  justify-content: center;
}

.item.item-center span {
  font-size: 12px;
  padding: 2px 4px;
  color: #fff;
  background-color: #dadada;
  border-radius: 3px;
  -moz-user-select: none; /*火狐*/
  -webkit-user-select: none; /*webkit浏览器*/
  -ms-user-select: none; /*IE10*/
  -khtml-user-select: none; /*早期浏览器*/
  user-select: none;
}

.avatar img {
  width: 42px;
  height: 42px;
  border-radius: 50%;
}

.input-area {
  border-top: 0.5px solid #e0e0e0;
  display: flex;
  flex-flow: column;
  background-color: #fff;
}

textarea {
  flex: 1;
  padding: 5px;
  font-size: 14px;
  border: none;
  cursor: pointer;
  overflow-y: auto;
  overflow-x: hidden;
  outline: none;
  resize: none;
}

.button-area {
  display: flex;
  height: 40px;
  margin-right: 10px;
  line-height: 40px;
  padding: 5px;
  justify-content: flex-end;
}

.button-area button {
  width: 80px;
  border: none;
  outline: none;
  border-radius: 4px;
  float: right;
  cursor: pointer;
}

/* 设置滚动条的样式 */
::-webkit-scrollbar {
  width: 10px;
}

/* 滚动槽 */
::-webkit-scrollbar-track {
  -webkit-box-shadow: inset006pxrgba(0, 0, 0, 0.3);
  border-radius: 8px;
}

/* 滚动条滑块 */
::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: rgba(0, 0, 0, 0);
  -webkit-box-shadow: inset006pxrgba(0, 0, 0, 0.5);
}
</style>